<script setup lang="ts">
import {getCategoryTree} from "@/api/AssetCategory";
import {getLocationTree} from "@/api/AssetLocation";
import {deptList, getAssetList, delAsset, sendAsset, editorAsset, copyAsset, pagination} from "@/api/AssetApi"
import {ref, onBeforeMount, nextTick, watch, reactive} from 'vue'
import {Plus, Refresh, Search} from '@element-plus/icons-vue'
import {ElTable, ElTableColumn, ElMessage, type UploadFile, type FormInstance,ElMessageBox } from 'element-plus'
import moment from "moment/moment";
type AssetType = {
  assetCode: string,
  model: string,
  name: string,
  categoryId: number | null,
  locationId: number | null,
  deptId: number | null,
  purchaseCost: number | null,
  unit: number | null,
  count: number | null,
  serialNumber: string | null,
  remark: string,
  pic: string,
  purchaseDate: string | null
  createTime: string | null,
}
const initFormData = () => ({
  assetCode: "",
  model: "",//型号规格
  name: "",//资产名称
  categoryId: null,//分类
  locationId: null,//位置
  deptId: null,//部门
  purchaseCost: null,//采购成本
  unit: null,
  count: null,
  serialNumber: null,//设备序列编号
  remark: "",//备注
  pic: "",//图片
  purchaseDate: null,//采购日期
  createTime: null,//创建日期
})
let assetData = ref<AssetType>(initFormData())


/********************上传单张图片*********************/
enum ImgType {
  JPG = 'image/jpg',
  JPEG = 'image/jpeg',
  PNG = 'image/png',
  GIF = 'image/gif',
  BMP = 'image/bmp',
  WEBP = 'image/webp',
  SVG = 'image/svg',
  UNKNOWN = 'image/unknown'
}

const imgUrl = ref<string>("");
const beforeUpload = (file: any) => {
  if (!Object.values(ImgType).includes(file["type"])) {
    ElMessage.error('请上传土图片');
    return false;
  }
  return true;
}
const assetUploadImg = (response: any, uploadFile: UploadFile) => {
  console.log(response.data)
  imgUrl.value = response.data;
  assetData.value.pic = response.data
}
/*********************新增资产***********************/
/*
* 获取产品属性结构分类/位置/部门
* */
const assetClassify = ref();
const assetLocation = ref();
const assetDept = ref();
const assetList = ref([]);
const getAssetClassifyLocation = async () => {
  const classify = await getCategoryTree();
  const location = await getLocationTree();
  const getDept = await deptList();
  assetClassify.value = classify.data;
  assetLocation.value = location.data;
  assetDept.value = getDept.data;

}
/*资产清单列表*/
const currentPage = ref(1)
const totalPage = ref(0)
const pageSize = ref(10)
const background = ref(false)
const disabled = ref(false)
currentPage.value = Number(sessionStorage.getItem("currentPage")) || 1;
const handleCurrentChange = (activePage: number) => {
  sessionStorage.setItem("currentPage", JSON.stringify(activePage));
  currentPage.value = activePage
  console.log(activePage, pageSize.value)
  assetListData(activePage, pageSize.value);
}
const assetListData = async (pageNum: number | string, pageSize: number) => {
  // const getAsset=await getAssetList();
  // assetList.value=getAsset.data;
  sessionStorage.setItem("currentPage", JSON.stringify(currentPage.value));
  const getAsset = await pagination(pageNum, pageSize);
  totalPage.value = getAsset.data.total;
  assetList.value = getAsset.data.list;
}
let isEditor = ref(false);
const assetDialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const addAssetShow = () => {
  isEditor.value = false;
  assetDialogVisible.value = true;
  imgUrl.value = ""
  nextTick(() => {
    assetData.value = JSON.parse(JSON.stringify(initFormData()))
    formRef.value?.resetFields()
  })
}

/*添加资产*/
const assetSubmit = (formEl: FormInstance | undefined) => {

  console.log(assetData.value, isEditor)
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (isEditor.value) {
        const result = await editorAsset(assetData.value)
        if (result.code === 200) {
          await assetListData(currentPage.value, pageSize.value)
          assetDialogVisible.value = false;
          console.log("修改", result)
        }
      } else {
        assetData.value.purchaseDate = moment().format("YYYY-MM-DD")
        assetData.value.createTime = moment().format("YYYY-MM-DD HH:mm:ss")
        console.log(assetData.value)
        const result = await sendAsset(assetData.value);
        console.log(result)
        if (result.code === 200) {
          await assetListData(1, pageSize.value);
          assetDialogVisible.value = false;
        }
        formEl.resetFields();
        console.log(assetData, result)
      }
    } else {
      console.log('error submit!')
    }
  })
  // assetDialogVisible.value = false;
}
/*********************编辑清单********************/
const assetEditor = (row: AssetType) => {
  isEditor.value = true;
  Object.assign(assetData.value, row)
  imgUrl.value = row.pic;
  assetDialogVisible.value = true;

}
/*******************删除清单********************/
const assetDel = async (id: number) => {
  ElMessageBox.confirm(
      '确定删除该资产信息吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const result =  delAsset(id);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        assetListData(currentPage.value, pageSize.value)
  }).catch(() => {
        console.log('取消删除')
  })

}
/**********复制************/
const assetCount = ref<number>(0)
const assetCopy = async (row: any) => {
  console.log(111,assetCount.value)
  if (assetCount.value=='' ) {
    assetCount.value = 1
    return ElMessage.error('资产数量不能为空！')
  }
  if (isNaN(assetCount.value) ) {
    assetCount.value = 1
    return ElMessage.error('资产数量必须为数值！')
  }
  if (assetCount.value<=0 ) {
    assetCount.value = 1
    return ElMessage.error('资产数量必须为正整数！')
  }

  await copyAsset(row.id, assetCount.value)
  await assetListData(currentPage.value, pageSize.value)
  assetCount.value = 0;
}
/*******************搜索*************************/
let searchVal = reactive<object>({name: "", assetCode: ""})
const searchAsset = async () => {
  const result = await getAssetList(searchVal);
  assetList.value = result.data;

}
const resetSearch = async () => {
  searchVal.name = "";
  searchVal.assetCode = "";
  await assetListData(currentPage.value, pageSize.value)
}
/******************生命周期******************88*/
onBeforeMount(async () => {
  await assetListData(currentPage.value, pageSize.value)
  await getAssetClassifyLocation();
})
</script>

<template>
  <div class="assetList">
    <el-space>
      <el-input

          placeholder="请输入资产编号"
          v-model="searchVal.assetCode"
          :clearable="true"
          :prefix-icon="Search"
      />
      <el-input
          style="width: 300px"
          placeholder="请输入资产名称"
          v-model="searchVal.name"
          :clearable="true"
          :prefix-icon="Search"
      >
        <template #append>
          <el-button type="primary" class="searchIcon" :icon="Search" @click="searchAsset">搜索
          </el-button>
        </template>
      </el-input>
      <el-button type="primary" plain :icon="Refresh" @click="resetSearch">重置
      </el-button>
      <el-button type="primary" plain class="btn-add" :icon="Plus" @click="addAssetShow">新增</el-button>
    </el-space>
    <el-table :data="assetList" height="88%" style="margin-top: 10px;cursor:pointer;">
      <el-table-column prop="assetCode" label="资产编号" align="left" width="160"/>
<!--      <el-table-column prop="assetCode" label="图片" align="left" width="160">
        <template #default="scope">
          <el-image style="width: 50px; height: 50px" :src="'http://localhost:8081/'+scope.row.pic" :fit="fit" />
        </template>
      </el-table-column>-->
      <el-table-column prop="batchNumber" label="批次号" align="center"/>
      <el-table-column prop="name" label="资产名称" align="center"/>
      <el-table-column prop="model" label="资产型号" align="center"/>
      <el-table-column prop="principalName" label="负责人" align="center"/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.status===0">闲置中</el-tag>
          <el-tag type="warning" v-if="scope.row.status===1">审批中</el-tag>
          <el-tag type="success" v-if="scope.row.status===2">使用中</el-tag>
          <el-tag type="warning" v-if="scope.row.status===3">维修中</el-tag>
          <el-tag type="danger" v-if="scope.row.status===4">已报废</el-tag>
          <el-tag type="info" v-if="scope.row.status===5">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="所属分类" width="130" align="center"/>
      <!--      <el-table-column prop="serialNumber" label="设备序列号" width="120"/>-->

      <el-table-column prop="deptName" label="所属仓库" align="center"/>
      <el-table-column prop="locationName" label="当前位置" align="center"/>
      <!--      <el-table-column prop="purchaseCost" label="采购成本" align="center"/>-->
      <!--      <el-table-column label="资产照片" width="120">-->
      <!--        <template #default="scope">-->
      <!--          <el-image :lazy="true" :src="scope.row.pic"-->
      <!--                    :preview-src-list="[scope.row.pic]" :z-index="999999"-->
      <!--                    :preview-teleported="true" style="width: 40px;height:40px;"></el-image>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column prop="assigned_to" label="领用人" width="100"/>-->
      <el-table-column prop="purchaseDate" label="采购日期" align="center"/>
      <!--      <el-table-column prop="createTime" label="创建时间" width="150"/>-->
      <!--      <el-table-column prop="updateTime" label="更新时间" width="150"/>-->
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="scope">
          <el-button link type="success" @click="assetEditor(scope.row)">
            <el-icon>
              <el-icon-edit/>
            </el-icon>
            编辑
          </el-button>
          <el-button link type="danger" @click="assetDel(scope.row.id)">
            <el-icon>
              <el-icon-delete/>
            </el-icon>
            删除
          </el-button>
          <el-popover placement="right" :width="350" trigger="hover">
            <template #reference>
              <el-button link type="primary">复制</el-button>
            </template>
            <el-form :inline="true"
                     style="display: flex;align-items: center;justify-content: space-between;font-size: 12px;">
              <el-space>资产数量：
                <el-input placeholder="请输入数量" v-model="assetCount"></el-input>
              </el-space>
              <el-button link type="primary" @click="assetCopy(scope.row)">确定</el-button>
            </el-form>
          </el-popover>

        </template>

      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :disabled="disabled"
        :background="background"
        layout=" slot,prev, pager, next"
        :total="totalPage"
        @current-change="handleCurrentChange"
    >
      <el-text key="1">总条数：{{ totalPage }}</el-text>
    </el-pagination>
    <!-----------------------新增资产--------------------------->
    <el-dialog
        v-model="assetDialogVisible"
        title="新增资产"
        width="58%"
    >
      <el-form :inline="true" label-width="100" :model="assetData" ref="formRef" label-position="right"
               class="addAssetFormStyle">
        <el-form-item label="型号：" prop="model" :rules="[{required:true,message:'请输入型号'}]">
          <el-input v-model="assetData.model" placeholder="请输入型号"/>
        </el-form-item>

        <el-form-item label="资产名称：" prop="name" :rules="[{required:true,message:'请输入资产名称'}]">
          <el-input v-model="assetData.name" placeholder="请输入资产名称"/>
        </el-form-item>
        <el-form-item label="资产分类：" prop="categoryId" :rules="[{required:true,message:'请选择资产分类'}]">
          <el-tree-select
              v-model="assetData.categoryId" placeholder="请选择资产分类"
              :data="assetClassify"
              node-key="id"
              :props="{label:'name',children:'children'}"
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="所在位置：" prop="locationId" :rules="[{required:true,message:'请选择资产位置'}]">
          <el-tree-select
              v-model="assetData.locationId" placeholder="请选择资产位置"
              :data="assetLocation"
              node-key="id"
              :props="{label:'locationName',children:'children'}"
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="所在部门：" prop="deptId" :rules="[{required:true,message:'请选择资产部门'}]">
          <el-tree-select
              v-model="assetData.deptId" placeholder="请选择资产部门"
              :data="assetDept"
              node-key="id"
              :props="{label:'deptName',children:'children'}"
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          ></el-tree-select>
        </el-form-item>
<!--        <el-form-item label="金额：" prop="purchaseCost" :rules="[{required:true,message:'请输入金额'}]">
          <el-input v-model="assetData.purchaseCost" placeholder="请输入金额"/>
        </el-form-item>-->
        <el-form-item label="计量单位：" prop="unit" :rules="[{required:true,message:'请填写计量单位'}]">
          <el-input v-model="assetData.unit" placeholder="请填写计量单位"/>
        </el-form-item>
        <el-form-item label="资产编号：">
          <el-input v-model="assetData.assetCode" placeholder="资产编号系统生成" clearable disabled/>
        </el-form-item>
<!--        <el-form-item label="设备序列号：">
          <el-input v-model="assetData.serialNumber" placeholder="序列号系统生成" disabled>
            <template #append>
              <el-button class="btnGre">生成</el-button>
            </template>
          </el-input>
        </el-form-item>-->
        <el-form-item label="备注：" style="width:100%;">
          <el-input type="textarea" resize="none" :rows="4" v-model="assetData.remark" placeholder="请填写备注"
                    clearable/>
        </el-form-item>
        <el-form-item label="资产照片：">
          <el-image size="48" v-if="imgUrl" :src="'http://localhost:8081/'+imgUrl" fit="cover"></el-image>
          <el-upload
              :action="$globalAttribute.baseUrl+'/common/upload'"
              name="file"
              :with-credentials="true"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="assetUploadImg"
          >
            <div class="uploadBtn">
              <el-icon class="iconfont icon-shangchuan"></el-icon>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assetDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="assetSubmit(formRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.assetList {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 5px;

  .el-space {
    margin-bottom: 10px;
  }


  .searchIcon, .btnGre {
    color: #ffffff;
    background-color: #409eff;
    border-bottom-left-radius: 0;
    border-top-left-radius: 0;
  }

  .searchIcon:hover, .btnGre:hover {
    background-color: #409eff;
    color: #ffffff;
  }

  .el-pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .addAssetFormStyle {
    display: flex;
    justify-content: space-between;
    align-content: stretch;
    flex-wrap: wrap;

    .el-input {
      width: 200px;
    }

    .el-image {
      width: 100px;
      height: 100px;
      margin: 0 15px;
    }

    .uploadBtn {
      width: 100px;
      height: 100px;
      border: 1px dashed #33cbcc;
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-shangchuan {
        color: #33cbcc;
        font-size: 32px;
      }
    }
  }
}
</style>